package com.k2data.k2app.service;

import com.k2data.k2app.domain.po.v1.Fault;
import com.k2data.k2app.mapper.FaultMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by k2data on 17-11-14.
 */
@Service
public class FaultService {

    private final FaultMapper faultMapper;

    @Autowired
    public FaultService(FaultMapper faultMapper) {
        this.faultMapper = faultMapper;
    }

    public int  delFault(Long id){
        Fault fault=faultMapper.selectById(id);
        if(fault.getParentId()==0){
            List<Fault> childs=faultMapper.getChildrens(fault.getId());
            if(!childs.isEmpty()){
                for (Fault child:childs) {
                    faultMapper.delFault(child.getId());
                }
            }
        }
        return faultMapper.delFault(id);
    }

    public int addFault(Fault fault){
        return faultMapper.insertSelective(fault);
    }

    public Fault getFault(Long id){
        return faultMapper.selectById(id);
    }

    public List<Fault> getFaultList(Long parentId,Boolean isTree){
        List<Fault> faultList=faultMapper.getNotDel();
        if(isTree != null && isTree){
            return buildTree(parentId,faultList);
        }else{
            return faultList;
        }
    }

    public List<Fault> buildTree(Long parentId,List<Fault> treeNodes) {
        List<Fault> trees = new ArrayList<>();
        Long pId = parentId == null?0:parentId;
        treeNodes.stream().filter(item -> item.getParentId().equals(pId)).forEach(item -> {
            trees.add(findChildren(item,treeNodes));
        });
            return trees;
    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    public static Fault findChildren(Fault treeNode,List<Fault> treeNodes) {
        treeNodes.stream().filter(item -> item.getParentId().equals(treeNode.getId())).forEach(item -> {
            System.out.println(treeNode.getId()+"  :"+item.getId());
            if (treeNode.getChildren() == null) {
                treeNode.setChildren(new ArrayList<>());
            }
            treeNode.getChildren().add(findChildren(item,treeNodes));
        });
        return treeNode;
    }

    public int updateFault(Fault fault){
       return  faultMapper.updateByPrimaryKeySelective(fault);
    }

}
